﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Dynamic;
using Htse.Blue.Models;
using Htse.Blue.Logic.Validation;
using Htse.Blue.Data;

namespace Htse.Blue.Logic
{
	public class CityDistanceService :
		ServiceBase<CityDistance, int, ICityDistanceRepository>,
		ICityDistanceService
	{
		public CityDistanceService(IValidationDictionary<CityDistance> validationDictionary)
			: base(validationDictionary, new CityDistanceRepository())
		{
		}

		public CityDistanceService(
			IValidationDictionary<CityDistance> validationDictionary,
			ICityDistanceRepository cityDistanceRepository)
			: base(validationDictionary, cityDistanceRepository)
		{
		}

		#region ICityDistanceService Members

		public PagedList<CityDistance> GetAll(
			int? page, int pageSize, string sortingParameter, string cityId)
		{
			if (string.IsNullOrEmpty(cityId))
			{
				return base.GetAll(page, pageSize, sortingParameter);
			}
			else
			{
				return GetAllFilteredByCity(page, pageSize, sortingParameter, cityId);
			}
		}

		#endregion

		protected override void ValidateAlways(
			CityDistance entityToValidate,
			IValidationDictionary<CityDistance> validationDictionary)
		{
			if (entityToValidate.FirstCityId == 0)
			{
				validationDictionary.AddError(c => c.City1, "La prima città è obbligatoria");
			}
			if (entityToValidate.SecondCityId == 0)
			{
				validationDictionary.AddError(c => c.City2, "La seconda città è obbligatoria");
			}
			if (entityToValidate.Distance <= 0)
			{
				validationDictionary.AddError(c => c.Distance, "La distanza deve essere un numero maggiore di zero");
			}
		}

		protected override void ValidateOnlyOnCreate(
			CityDistance entityToValidate,
			IValidationDictionary<CityDistance> validationDictionary)
		{
			if (repository.ExistWithSameCities(entityToValidate))
			{
				validationDictionary.AddError(c => c.City1, c => c.City2, "La distanza tra le due città scelte è già presente");
			}
		}

		private PagedList<CityDistance> GetAllFilteredByCity(int? page, int pageSize, string sortingParameter, string cityId)
		{
			IQueryable<CityDistance> all;

			if (string.IsNullOrEmpty(sortingParameter))
			{
				all = base.GetAll();
			}
			else
			{
				all = base.GetAll().OrderBy(sortingParameter);
			}

			var filtered =
				from a in all
				where a.City1.Id.ToString() == cityId || a.City2.Id.ToString() == cityId
				select a;

			return filtered.ToPagedList(page, pageSize, sortingParameter, cityId);
		}
	}
}
